package cn.mabach.oauth2.config;

import cn.mabach.oauth2.project.feign.MemberServiceFeign;
import cn.mabach.oauth2.utils.UserJwt;
import cn.mabach.member.entity.MemberEntity;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class CustomUserDetailsService implements UserDetailsService  {

    @Autowired
    private MemberServiceFeign memberServiceFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        MemberEntity entity = memberServiceFeign.getMemberByUsername(username).getData();

        if (entity==null){
            throw new UsernameNotFoundException("用户名错误");
        }
        //根据封装权限
        List<String> permsList = memberServiceFeign.getPermsByUsername(username).getData();
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (String perm : permsList) {
            grantedAuthorities.add(new SimpleGrantedAuthority(perm));
        }

        UserJwt userJwt = new UserJwt(username, entity.getPassword(), grantedAuthorities);

        userJwt.setIcon(entity.getQqIcon());
        userJwt.setNickname(entity.getQqNickname());
        return userJwt;


    }



//
}
